/**
* @Author: zmx
* @Date: 2023/9/26
* @Description:
*/
<template>
  <el-dialog :title="titleFront + '风险评估引擎规则'" :visible.sync="show" append-to-body width="50%" :before-close="handleClose">
    <el-form :model="formInline">
      <el-form-item label="引擎规则名称：">
        <span v-if="formInline.type === 'detail'">{{formInline.ruleName}}</span>
        <el-input v-else v-model="formInline.ruleName" placeholder="请输入引擎规则名称" maxlength="100" show-word-limit></el-input>
      </el-form-item>
      <el-form-item label="对象类型：">
        <el-select
          v-model="formInline.objectType"
          value-key="id"
          filterable
          @change="changeType"
          :disabled="formInline.type === 'detail'"
        >
          <el-option
            v-for="item in optionsTypeList"
            :key="item.id"
            :label="item.itemObjectName"
            :value="item.id"
          />
        </el-select>
      </el-form-item>
      <el-form-item label="引擎规则公式：">
        <span v-if="formInline.type === 'detail'">{{formInline.ruleContent.substring(1)}}</span>
        <el-table v-else :data="tableData" style="width: 100%" :header-cell-style="{background:'#006175',color:'#fff'}">
          <el-table-column prop="itemSymbol" label="计算符号">
            <template v-slot="scope">
              <el-select
                v-model="tableData[scope.$index]['itemSymbol']"
                value-key="id"
                filterable
                @change="changeTable"
                :disabled="scope.$index === 0"
              >
                <el-option
                  v-for="item in optionsList"
                  :key="item.name"
                  :label="item.name"
                  :value="item.name"
                />
              </el-select>
            </template>
          </el-table-column>
          <el-table-column prop="powerValue" label="权重">
            <template v-slot="scope">
              <el-input v-model="tableData[scope.$index]['powerValue']" placeholder="请输入权重" @input="$forceUpdate()" @change="changePower(scope.$index)"></el-input>
            </template>
          </el-table-column>
          <el-table-column prop="itemId" label="算法指标">
            <template v-slot="scope">
              <el-select
                v-model="tableData[scope.$index]['itemId']"
                value-key="id"
                filterable
                @change="changeTable"
              >
                <el-option
                  v-for="item in itemData"
                  :key="item.id"
                  :label="item.itemName"
                  :value="item.id"
                />
              </el-select>
            </template>
          </el-table-column>
          <el-table-column label="操作" width="100">
            <template v-slot="scope">
              <el-button class="common-btn" @click="addRule()">+</el-button>
              <el-button class="delete-btn" @click="deleteRule(scope.$index)" v-show="tableData.length>1">-</el-button>
            </template>
          </el-table-column>
        </el-table>
      </el-form-item>
      <el-form-item label="引擎规则公式预览：" v-show="formInline.type !== 'detail'">{{formInline.ruleContent.substring(1)}}</el-form-item>
      <el-form-item label="引擎规则内容：">{{formInline.content}}</el-form-item>
    </el-form>
    <span slot="footer" class="dialog-footer">
      <el-button type="primary" @click="checkBtn" v-if="formInline.type !== 'detail'">确 认</el-button>
      <el-button @click="handleClose">取 消</el-button>
    </span>
  </el-dialog>
</template>

<script>
import {getRiskItemList} from "../../api/risk/riskItem";
import {getItemDictObject} from "../../api/risk/commonDict";

export default {
  props: ['RuleDialogShow', 'ruleParam'], //接受父组件传递过来的数据
  data() {
    return {
      show: false, //弹窗默认隐藏
      formInline: {
        ruleName:'',
        ruleContent:'',
        content:'',
      },
      tableData: [{itemSymbol:'+',itemId:'',powerValue:''}],
      optionsTypeList: [],
      itemData: [],
      optionsList:[
        {
          name:'+',
        },
        {
          name:'-',
        },
        {
          name:'*',
        },
        {
          name:'/',
        }
      ],
      titleFront: '查看'
    };
  },
  mounted() {
    //显示弹窗
    this.formInline = JSON.parse(JSON.stringify(this.ruleParam))
    this.initList()
    this.initParam()
  },
  methods: {
    handleClose() {
      //关闭弹窗
      this.show = false
      this.$emit('closeDialog')
    },
    checkBtn() {
      //确定按钮
      if (this.checkParam()) {
        this.formInline.itemList = this.tableData
        this.$emit('inputData', this.formInline)   //发送数据到父组件
        this.handleClose()
      }
    },
    checkParam() {
      if (!this.formInline.ruleName) {
        this.$message({ message: '请输入引擎规则名称', type: 'warning' })
        return false
      }
      if (!this.formInline.objectType) {
        this.$message({ message: '请选择对象类型', type: 'warning' })
        return false
      }
      let result = true
      this.tableData.forEach(item => {
        if (!item.itemSymbol) {
          this.$message({ message: '请选择计算符号', type: 'warning' })
          result = false
          return
        }
        if (!item.powerValue) {
          this.$message({ message: '请输入权重', type: 'warning' })
          result = false
          return
        }
        if (!item.itemId) {
          this.$message({ message: '请选择算法指标', type: 'warning' })
          result = false
        }
      })
      if (result) {
        let sumPower = 0
        let prev = 0
        let prevSymbol = '+'
        for (let i = 0; i < this.tableData.length; i++) {
          let item = this.tableData[i];
          if (item.itemSymbol === '+' || item.itemSymbol === '-') {
            sumPower += this.getSumN(prev, prevSymbol)
            prev = this.getNumber(item.powerValue)
            prevSymbol = item.itemSymbol
          } else {
            if (item.itemSymbol === '*') {
              prev *= this.getNumber(item.powerValue)
            }
            if (item.itemSymbol === '/') {
              prev /= this.getNumber(item.powerValue)
            }
          }
          if (i === this.tableData.length - 1) {
            sumPower += this.getSumN(prev, prevSymbol)
          }
        }
        if (sumPower.toFixed(5) !== Number(1).toFixed(5)) {
          this.$message({ message: '权重总和不为1', type: 'warning' })
          return false
        }
      }
      return result
    },
    getSumN(value, symbol) {
      if (symbol === '-') {
        return -value
      }
      return value
    },
    getNumber(number) {
      if (number.includes('/')) {
        let nums = number.split(/\//)
        return parseInt(nums[0]) / parseInt(nums[1])
      } else {
        return parseFloat(number)
      }
    },
    changeType() {
      this.initItem()
      this.tableData.forEach(item => {
        item.itemId = ''
      })
      this.changeTable()
    },
    async initItem() {
      await getRiskItemList({itemType:this.formInline.objectType}).then((res) => {
        if (res) {
          this.itemData = res
        }
      }).catch(err => {
        this.$message({ message: '服务器异常：' + err, type: 'warning' })
      })
    },
    changePower(index) {
      let reg = /^(\d+\/\d+|\d+(\.\d+)?)$/
      if (this.tableData[index].powerValue.match(reg)) {
        this.changeTable()
      } else {
        this.tableData[index].powerValue = ''
        this.$message({ message: '权重为不大于1的小数或者分数', type: 'warning' })
      }
    },
    changeTable() {
      let tmpContent = ''
      let content = ''
      this.tableData.forEach(item => {
        if (item.powerValue && item.itemSymbol && item.itemId) {
          tmpContent += item.itemSymbol + this.itemData.find(obj => obj.id === item.itemId).itemTypeSymbol + '*' + item.powerValue
          content += item.itemSymbol + this.itemData.find(obj => obj.id === item.itemId).itemName + '*' + item.powerValue
        }
      })
      this.formInline.ruleContent = tmpContent
      this.formInline.content = content.substring(1)
    },
    addRule() {
      this.tableData.push({itemSymbol:'',itemId:'',powerValue:''})
    },
    deleteRule(index) {
      this.tableData.splice(index, 1)
      if (index === 0) {
        this.tableData[0].itemSymbol = '+'
      }
      this.changeTable()
    },
    initParam() {
      if (this.formInline.itemList) {
        let content = ''
        this.formInline.itemList.forEach(item => {
          content += item.itemSymbol + item.itemName + '*' + item.powerValue
        })
        this.formInline.content = content.substring(1)
      }
      if (this.formInline.type === 'add') {
        this.titleFront = '新建'
      } else if (this.formInline.type === 'edit') {
        this.titleFront = '编辑'
      }
      this.show = this.RuleDialogShow
    },
    async initList() {
      await getItemDictObject().then((res)=>{
        if(res){
          this.optionsTypeList = res
        }
      }).catch(err => {
        this.$message({ message: '服务器异常：' + err, type: 'warning' })
      })
      if (this.formInline.objectType) {
        await this.initItem()
      }
      if(this.formInline.ruleContent) {
        let reg = /[+/*-]?[A-Za-z]\w*\*(\d+\/\d+|\d+(\.\d+)?)/g
        this.formInline.ruleContent.match(reg).forEach((item, index) => {
          let line = item.split(/[A-Za-z]\w*\*/)
          this.$set(this.tableData, index, {})
          this.$set(this.tableData[index], 'itemSymbol', line[0] ? line[0] : '+')
          this.$set(this.tableData[index], 'powerValue', line[1])
          this.$set(this.tableData[index], 'itemId', this.itemData.find(obj => obj.itemTypeSymbol === item.substring(1, item.lastIndexOf('\*'))).id)
          this.changeTable()
        })
      }
    },
  }
};
</script>

<style scoped>

</style>
